package com.casic.modules.activiti.service;

import com.casic.modules.activiti.entity.Task;
import com.casic.modules.activiti.util.JqGridPageView;
import com.casic.modules.activiti.util.WorkFlowUtils;
import com.casic.modules.sys.entity.SysUserEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.activiti.engine.FormService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.impl.form.TaskFormDataImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.TaskQuery;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.Map.Entry;

/**
 * @author htkjsx
 * @version 2016年5月20日 下午3:16:07
 */
@Service
public class ActTaskService {
	@Autowired
	private TaskService taskService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private FormService formService;
	@Autowired
	private IdentityService identityService;
	
	protected ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * 
	 * @Title getList
	 * @Description (查询待办事项列表)
	 * @author 颜金星
	 * @create 2017年5月4日-下午2:07:50
	 * @Param @param act
	 * @Param @return
	 * @return PageInfo<Task>
	 * @throws
	 */
	public JqGridPageView<Task> getTaskList(Map<String, Object> params){
		JqGridPageView<Task> gridView=new JqGridPageView<Task>();
		int firstResult = 1;
    	int maxResults = 10;
    	if(params.get("page")!=null){
    		firstResult=Integer.parseInt((String)params.get("page"));
    	}
    	if(params.get("rows")!=null){
			maxResults = (Integer)params.get("rows");
    	}
		SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		String userId=userEntity.getUserId()+"";
		// =============== 已经签收的任务  ===============
		TaskQuery todoTaskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(userId).active().orderByTaskId().desc();
		// 设置查询条件
//		if (StringUtils.isBlank(act.getProcDefKey())){
//			todoTaskQuery.processDefinitionKey(act.getProcDefKey());
//		}
//		if (act.getBeginDate() != null){
//			todoTaskQuery.taskCreatedAfter(act.getBeginDate());
//		}
//		if (act.getEndDate() != null){
//			todoTaskQuery.taskCreatedBefore(act.getEndDate());
//		}
		// 查询列表
		List<org.activiti.engine.task.Task> todoList = todoTaskQuery.listPage((firstResult - 1)*maxResults, maxResults);
		org.activiti.engine.task.Task task=null;
		List<Task> dataList=new ArrayList<Task>();
		Task dataTask=null;
		com.casic.modules.activiti.entity.ProcessDefinition processDefinitionData=null;
		for(int i=0;i<todoList.size();i++){
			task=todoList.get(i);
			ProcessDefinition processDefinition= WorkFlowUtils.getProcessDefinitionByProcDefId(task.getProcessDefinitionId(), repositoryService);
			processDefinitionData=new com.casic.modules.activiti.entity.ProcessDefinition();
			dataTask=new Task();
			processDefinitionData.setId(processDefinition.getId());
			processDefinitionData.setName(processDefinition.getName());
			processDefinitionData.setKey(processDefinition.getKey());
			processDefinitionData.setVersion(processDefinition.getVersion()+"");
			processDefinitionData.setResourceName(processDefinition.getResourceName());
			processDefinitionData.setDiagramResourceName(processDefinition.getDiagramResourceName());
			processDefinitionData.setDeploymentId(processDefinition.getDeploymentId());
			dataTask.setProcessDefinition(processDefinitionData);
			dataTask.setProcessDefinitionId(task.getProcessDefinitionId());
			dataTask.setName(task.getName());
			dataTask.setAssignee(task.getAssignee());
			dataTask.setOwner(task.getOwner());
			dataTask.setProcessInstanceId(task.getProcessInstanceId());
			dataTask.setId(task.getId());
			System.out.println(task.getProcessVariables());
			System.out.println(task.getTaskLocalVariables());
			System.out.println(task.getTenantId());
			System.out.println(task.getCategory());
			System.out.println(task.getFormKey());
			dataList.add(dataTask);
		}
		long count=todoTaskQuery.count();
		gridView.setCurrentPage((firstResult - 1) * maxResults);
		gridView.setMaxResults(maxResults);
		gridView.setRecords(count);
		gridView.setRows(dataList);
		return gridView;
	}
	/**
	 * 
	 * @Title claim
	 * @Description (签收任务)
	 * @author 颜金星
	 * @create 2017年5月15日-下午2:12:59
	 * @Param @param params
	 * @return void
	 * @throws
	 */
	public void claim(Map<String, Object> params){
		SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		String userId=userEntity.getUserId()+"";
		String taskId=(String)params.get("taskId");
		taskService.claim(taskId, userId);
	}
	
	public Map<String, Object> getTaskForm(Map<String, Object> params){
		String taskId=(String)params.get("taskId");
		Map<String, Object> result = new HashMap<String, Object>();
        TaskFormDataImpl taskFormData = (TaskFormDataImpl) formService.getTaskFormData(taskId);
        // 设置task为null，否则输出json的时候会报错
        taskFormData.setTask(null);
        result.put("taskFormData", taskFormData);
    /*
     * 读取enum类型数据，用于下拉框
     */
        List<FormProperty> formProperties = taskFormData.getFormProperties();
        for (FormProperty formProperty : formProperties) {
            Map<String, String> values = (Map<String, String>) formProperty.getType().getInformation("values");
            if (values != null) {
                for (Entry<String, String> enumEntry : values.entrySet()) {
                    //logger.debug("enum, key: {}, value: {}", enumEntry.getKey(), enumEntry.getValue());
                }
                result.put(formProperty.getId(), values);
            }
        }
        return result;
	}
	/**
	 * 
	 * @Title complete
	 * @Description (办理任务流程)
	 * @author 颜金星
	 * @create 2017年5月15日-下午2:43:27
	 * @Param @param params
	 * @return void
	 * @throws
	 */
	public void complete(Map<String, Object> params,HttpServletRequest request){
		String taskId=(String)params.get("taskId");
		String processInstanceId=(String)params.get("processInstanceId");
		SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		String userId=userEntity.getUserId()+"";
		Map<String, String> formProperties = new HashMap<String, String>();
        // 从request中读取参数然后转换
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
        for (Entry<String, String[]> entry : entrySet) {
            String key = entry.getKey();
            formProperties.put(key,request.getParameter(key) );
        }
        String fullMessage="";
		 fullMessage=(String)params.get("fullMessage");
		 if(fullMessage==null){
		     fullMessage="";
         }
      //  logger.debug("start form parameters: {}", formProperties);
        try {
        	Map<String, Object> vars= Maps.newHashMap();
        	vars.put("fullMessage", fullMessage);
        	vars.put("title", "任务办理");
        	taskService.addComment(taskId, processInstanceId,fullMessage );
            identityService.setAuthenticatedUserId(userId);
            formService.submitTaskFormData(taskId, formProperties);
         //   taskService.complete(taskId, vars);
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
	}
}
